﻿using System;
using System.IO;
using System.Xml.Serialization;

namespace ManagedServices.UI.Web.Controllers
{
    public class Utility
    {
        public const string InstallDirectory = "UnzipDirectory";
        public const string NewSubServiceDirectory = "NewSubServiceDirectory";

        public static void SetupInstallDirectory()
        {
            string unzipDir = GetInstallDirectory();
            if (!Directory.Exists(unzipDir))
            {
                Directory.CreateDirectory(unzipDir);
            }

            foreach (var item in Directory.GetDirectories(unzipDir))
            {
                Directory.Delete(item, true);                
            }

            foreach (var fileName in Directory.GetFiles(unzipDir))
            {
                File.Delete(fileName);   
            }
        }

        public static string GetInstallDirectory()
        {
            return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, InstallDirectory);
        }

        /// <summary>
        /// Serializes an instance and returns the serialized XML string using XML Serializer
        /// </summary>
        /// <typeparam name="TTypeToSerialize">the type to serialize</typeparam>
        /// <param name="instance">the instance of the type to serialize</param>
        /// <returns>the serialized output</returns>
        public static string XmlSerialize<TTypeToSerialize>(TTypeToSerialize instance) where TTypeToSerialize : class
        {
            XmlSerializer ser = new XmlSerializer(typeof(TTypeToSerialize));
            MemoryStream mStream = new MemoryStream();
            ser.Serialize(mStream, instance);
            mStream.Position = 0;
            using (StreamReader sRdr = new StreamReader(mStream))
            {
                return sRdr.ReadToEnd();
            }
        }

        /// <summary>
        /// DeSerializes an instance from the serialized XML string using XML Serializer
        /// </summary>
        /// <typeparam name="TTypeToDeserialize">the type to deserialize</typeparam>
        /// <param name="serializedInstance">the serialized input</param>
        /// <returns>the deserialized instance </returns>
        public static TTypeToDeserialize XmlDeSerialize<TTypeToDeserialize>(string serializedInstance) where TTypeToDeserialize : class
        {
            XmlSerializer ser = new XmlSerializer(typeof(TTypeToDeserialize));
            MemoryStream mStream = new MemoryStream();
            StreamWriter sw = new StreamWriter(mStream);
            sw.Write(serializedInstance);
            sw.Flush();
            mStream.Position = 0;
            return (TTypeToDeserialize)ser.Deserialize(mStream);
        }
    }
}